package main

import (
	"fmt"
	"log"
	"ollama-go/config"
	_ "ollama-go/controller"
	"ollama-go/toolkit"
	"os"
	"os/exec"
	"os/signal"
	"runtime/debug"

	"github.com/androidsr/sc-go/proxy"
	"github.com/androidsr/sc-go/sgin"
	"github.com/androidsr/sc-go/sgorm"
	"github.com/androidsr/sc-go/sminio"
	"github.com/androidsr/sc-go/sno"
	"github.com/lesismal/nbio/nbhttp/websocket"
)

func main() {
	defer func() {
		err := recover()
		if err != nil {
			log.Printf("panic recovered:\n%s\n%s", err, debug.Stack())
		}
	}()
	log.SetFlags(log.Llongfile | log.LstdFlags)

	if config.CFG.Llm.Ollama.Enable {
		toolkit.NewOllamaEmbedding()
	} else if config.CFG.Llm.Openai.Enable {
		toolkit.NewOpenaiEmbedding()
	}
	sgorm.DB = sgorm.New(config.CFG.Sc.Gorm)
	sno.New(*config.CFG.Sc.Snowflake)
	sminio.New(config.CFG.Sc.Minio)
	router := sgin.New(config.CFG.Sc.Gin)
	router.Cors()
	router.WebToken(config.CFG.Sc.Jwt)

	/* socket := wsocket.NewServer(router.Engine)

	socket.OnMessage(wsMessage)
	err := socket.Start(":10884", 100000)
	if err != nil {
		fmt.Printf("启动Web Socket 服务失败, %v", err)
		return
	} */
	go func() {
		router.RunServer()
	}()

	cmd := exec.Command(`cmd`, `/c`, `start`, fmt.Sprintf("http://localhost:%s", config.CFG.Sc.Proxy.Port))
	cmd.Start()
	proxy.New(config.CFG.Sc.Proxy)

	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	<-interrupt
	//socket.Close()
}

func wsMessage(conn *websocket.Conn, messageType websocket.MessageType, data []byte) {
	fmt.Println("收到消息", string(data))
}
